package ce.com.cenewbluesdk.ota.ota_modea;


import ce.com.cenewbluesdk.uitl.ByteUtil;

/**
 * Created by Administrator on 2015/12/25 0025.
 */
public class DealOtaFile {

    byte[] fileBytes;

    private OTASendEntity mOTASendEntity;

//    private String OTAFileErrorString = "";

    public DealOtaFile(byte[] fileBytes) throws OtaFileException {
        this.fileBytes = fileBytes;
        resolveFile();
    }

    public DealOtaFile(String otaFilePath) throws OtaFileException {
        this(OtaUtil.getBytes(otaFilePath));
    }

    public OTASendEntity getOTASendEntity() {
        return mOTASendEntity;
    }

//    public String getOTAFileErrorString() {
//        if (TextUtils.isEmpty(OTAFileErrorString)) {
//            if (mOTASendEntity != null) {
//                return mOTASendEntity.getOTAItemErrorString();
//            } else {
//                return "处理文件的时候没有报错，理论上mOTASendEntity 不会是空，但是现在null 了 ";
//            }
//        } else {
//            return OTAFileErrorString;
//        }
//    }

    public void resolveFile() throws OtaFileException {
        mOTASendEntity = null;
        /*
            文件协议：
                1 前面7个字节是对文件的描述
                2 从低8个个字节开始，到文件的最后是所有的设计数据
                    也就是OTASendEntity
        */
        if (fileBytes == null || fileBytes.length < 5000) {
            throw new OtaFileException("文件异常  是空，或者长度小于100");
        }
        byte[] fileLenbytes = new byte[]{fileBytes[0], fileBytes[1], fileBytes[2], fileBytes[3]};
        //整个文件的长度
        int fileLen = ByteUtil.byte4ToInt(fileLenbytes);
        //整个文件的CRC值
        int fileCrc = ByteUtil.byte2ToInt(new byte[]{fileBytes[4], fileBytes[5]});
        if (fileLen != fileBytes.length) {
            throw new OtaFileException("文件异常  文件解析出来的长度，不等于文件的实际长度");
        }

        byte[] crcBytes = new byte[fileLen - 6];
        System.arraycopy(fileBytes, 6, crcBytes, 0, fileLen - 6);
        if (!OtaUtil.checkCrc16OK(fileCrc, crcBytes)) {
            throw new OtaFileException("文件异常  文件的crc校验不正确");
        }
        //文件中升级的实体个数，一般是固定的
        int itemCount = crcBytes[0];
        byte[] itemDate = new byte[fileLen - 7];
        System.arraycopy(crcBytes, 1, itemDate, 0, fileLen - 7);
        mOTASendEntity = new OTASendEntity(itemDate, itemCount);

        OtaUtil.otaLog("fileCrc=" + fileCrc + "fileLen=" + fileLen);
    }

}
